<template>
    <div v-loading="allLoading" :element-loading-text="loadingText">
        <div class="header">
            <h3>Translate PDF through ChatGLM-4</h3>
        </div>

        <div class="upload-card">
            <el-card style="width: 600px">
                <template #header>
                    <div class="card-header">
                        <div class="upload-card-header">
                            <span>Upload</span>
                            <div>
                                <el-input style="width: 140px;margin-right: 8px;" v-model="fromLanguage"
                                    disabled></el-input>
                                <el-select v-model="toLanguage" placeholder="目标语言" style="width: 140px"
                                    :disabled="selectLangFlag">
                                    <el-option v-for="item in langOptions" :key="item" :label="item" :value="item" />
                                </el-select>
                            </div>
                        </div>
                    </div>
                </template>
                <div class="upload-content">
                    <div> <el-upload ref="uploadRef" class="upload-demo" :before-upload="beforeUpload"
                            :action="actionUrl" :on-success="handleSuccess" :file-list="fileList" :limit="1">
                            <template #trigger>
                                <el-button type="primary">select file</el-button>
                            </template>
                            <el-button class="ml-3" style="margin-left:10px" type="success"
                                @click="handleStartTranslation">
                                Start Translation
                            </el-button>
                            <template #tip>
                                <div class="el-upload__tip text-red">
                                    limit 1 file, new file will cover the old file
                                </div>
                            </template>
                        </el-upload></div>
                </div>
            </el-card>
        </div>

        <div class="download-card">
            <el-card style="width: 600px">
                <template #header>
                    <div class="card-header">
                        <span>Download</span>
                    </div>

                </template>
                <el-button type="primary" :disabled="downloadDisabled" @click="handleDownload">
                    Download<el-icon class="el-icon--right">
                        <Download />
                    </el-icon>
                </el-button>
            </el-card>
        </div>
    </div>
</template>
<script>
import { Download } from '@element-plus/icons-vue'
import { defineComponent, ref, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus';


export default defineComponent({
    name: "HomeIndex",
    components: {
        Download
    },
    setup() {
        const downLoading = ref(false)
        const downloadDisabled = ref(true)
        const fromLanguage = ref("当前语言")
        const toLanguage = ref()
        const actionUrl = "http://127.0.0.1:5000/upload"
        const ACCEPTED_EXTENSIONS = ['pdf'];
        const fileList = ref([]);
        const langOptions = ref([])
        const selectLangFlag = ref(true)
        const allLoading = ref(false)
        const filepath = ref()
        const { proxy } = getCurrentInstance();
        const loadingText = ref()
        const outputPath = ref()

        const beforeUpload = function (file) {
            const extension = file.name.split('.').pop().toLowerCase();
            if (!ACCEPTED_EXTENSIONS.includes(extension)) {
                ElMessage({
                    type: 'error',
                    message: '仅支持pdf格式的文件',
                });
                return false;
            }
            loadingText.value = "正在获取pdf文件语言..."
            allLoading.value = true
            return true;
        }

        const handleSuccess = (response, file, fileList) => {
            console.log('上传成功:', response, file, fileList)
            if (response.code === 0) {
                selectLangFlag.value = false
                fromLanguage.value = response.data.language
                langOptions.value = response.data.language_list
                filepath.value = response.data.filepath
                ElMessage({
                    type: 'success',
                    message: `获取语言成功, 文件语言为${response.data.language}`,
                });
            } else {
                ElMessage({
                    type: 'error',
                    message: response.data.msg,
                });
            }
            allLoading.value = false
            // 执行上传成功后的操作，例如显示上传成功的消息或者跳转页面
        }

        const handleStartTranslation = () => {
            if (!filepath.value || !toLanguage.value) {
                return ElMessage({
                    type: 'error',
                    message: 'filepath and to_language cannot be empty',
                });
            }
            loadingText.value = "正在翻译pdf..."
            allLoading.value = true
            proxy.$axios.post('/start', { "filepath": filepath.value, "to_language": toLanguage.value }).then(res => {
                console.log(res);
                if (res.data.code === 0) {
                    downloadDisabled.value = false
                    outputPath.value = res.data.data.output_path
                    return ElMessage({
                        type: 'success',
                        message: '翻译成功, 请点击download下载翻译后的文件',
                    });
                } else {
                    return ElMessage({
                        type: 'error',
                        message: res.data.msg,
                    });
                }
            }).finally(() => {
                allLoading.value = false
            })
        }

        const handleDownload = function () {
            proxy.$axios.get('/download', {
                params: { filepath: outputPath.value },
                responseType: 'blob' // 设置响应类型为 blob
            })
                .then(response => {
                    // 创建一个 blob 对象，并将响应的数据放入其中
                    const blob = new Blob([response.data]);
                    // 通过 URL.createObjectURL() 创建一个下载链接
                    const url = URL.createObjectURL(blob);
                    // 创建一个 <a> 元素，用于触发下载
                    const link = document.createElement('a');
                    link.href = url;
                    // 设置下载的文件名
                    link.setAttribute('download', 'filename.md');
                    // 将 <a> 元素添加到 DOM 中
                    document.body.appendChild(link);
                    // 触发点击事件，开始下载
                    link.click();
                    // 下载完成后，移除 <a> 元素和 URL 对象
                    link.remove();
                    URL.revokeObjectURL(url);
                })
                .catch(error => {
                    console.error('下载文件失败:', error);
                });
        }

        return {
            fromLanguage,
            downloadDisabled,
            beforeUpload,
            handleSuccess,
            fileList,
            actionUrl,
            handleStartTranslation,
            langOptions,
            selectLangFlag,
            allLoading,
            toLanguage,
            loadingText,
            handleDownload
        }
    }
})

</script>
<style scoped>
.header {
    display: flex;
    justify-content: center;
}

.upload-card-header {
    display: flex;
    justify-content: space-between;
}

.upload-card {
    margin-top: 10px;
    display: flex;
    justify-content: center;
}

.download-card {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.upload-content {
    display: flex;
    justify-content: space-between
}
</style>